/**
 * Copyright (C) 2010 David Simonek <dafesimonek@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AddSongsPanel.java
 *
 * Created on Aug 6, 2010, 11:24:41 PM
 */

package org.dafe.partyband.gui.concerts;

import com.db4o.query.Predicate;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.SortOrder;
import javax.swing.Timer;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.dafe.partyband.db.api.ISong;
import org.dafe.partyband.db.api.queries.ISongQuery;
import org.dafe.partyband.db.model.Song;
import org.dafe.partyband.db.api.DbManager;
import org.dafe.partyband.gui.Utilities;
import org.dafe.partyband.importer.api.IImporterServices;
import org.dafe.partyband.importer.api.INameEncoder;
import org.jdesktop.swingx.JXTextField;
import org.jdesktop.swingx.decorator.HighlighterFactory;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;

/**
 *
 * @author dafe
 */
public class AddSongsPanel extends javax.swing.JPanel {

    private static final ISongQuery songQuery = DbManager.getBandManager().getQueriesLookup().lookup(ISongQuery.class);
    private static final INameEncoder nameEncoder = Lookup.getDefault().lookup(IImporterServices.class).getNameEncoder();

    private final Timer searchTimer;
    private JButton addButton;
    private boolean filterEmptyMode = false;
    
    private JXTextField searchTipText;

    /** Creates new form AddSongsPanel */
    public AddSongsPanel() {
        initComponents();
        
        searchTipText = new JXTextField(
            NbBundle.getMessage(AddSongsPanel.class, "AddSongsPanel.searchTipText"));
        searchTipText.setHorizontalAlignment(JXTextField.CENTER);
        
        songList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        songList.setAutoCreateRowSorter(true);
        songList.setHighlighters(HighlighterFactory.createSimpleStriping());
        songList.setSortOrder(SortOrder.ASCENDING);
        songList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                checkValidity();
            }
        });

        searchTimer = new Timer(250, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String searchText = searchField.getText().trim();
                if (searchText.isEmpty()) {
                    setFilterEmptyMode(true);
                } else {
                    setFilterText(searchText);
                    setFilterEmptyMode(false);
                    if (songList.getElementCount() == 1) {
                        songList.setSelectedIndex(0);
                    }
                }
            }
        });
        searchTimer.setRepeats(false);

        searchField.getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
                searchTimer.restart();
            }

            public void removeUpdate(DocumentEvent e) {
                searchTimer.restart();
            }

            public void changedUpdate(DocumentEvent e) {
                searchTimer.restart();
            }
        });
        
        setFilterEmptyMode(true);
    }

    public void attachAddButton (JButton addButton) {
        this.addButton = addButton;
        checkValidity();
    }

    public List<? extends ISong> getSelectedSongs () {
        int[] indices = songList.getSelectedIndices();
        List<ISong> result = new ArrayList<ISong>(indices.length);
        SongListModel songListModel = (SongListModel)songList.getModel();
        
        for (int i = 0; i < indices.length; i++) {
            result.add(songListModel.getSongAt(songList.convertIndexToModel(indices[i])));
        }
        
        return result;
        
    }

    public void clearSearchText () {
        searchField.setText("");
        songList.clearSelection();
    }
    
    private void setFilterEmptyMode(boolean filterEmpty) {
        if (filterEmptyMode == filterEmpty) {
            return;
        }
        filterEmptyMode = filterEmpty;
        
        if (filterEmptyMode) {
            jScrollPane1.setViewportView(searchTipText);
            jScrollPane1.setEnabled(false);
        } else {
            jScrollPane1.setViewportView(songList);
            jScrollPane1.setEnabled(true);
        }
    }

    @Override
    public void addNotify() {
        super.addNotify();
        searchField.requestFocusInWindow();
    }

    private void checkValidity() {
        if (addButton != null) {
            addButton.setEnabled(!songList.isSelectionEmpty());
        }
    }
    
    public void setFilterText(String text) {
        final String localText = text.trim();
        List<? extends ISong> songs = songQuery.findSongs(text, new Predicate<ISong>() {
            @Override
            public boolean match(ISong song) {
                return Utilities.isSongMatch(song, localText);
            }
        });
        
        songList.setModel(new SongListModel(songs));
    }
    

    private static class SongListModel extends AbstractListModel {

        private List<? extends ISong> songs;

        public SongListModel(List<? extends ISong> songs) {
            this.songs = songs;
        }
        
        public int getSize() {
            return songs == null ? 0 : Math.min(songs.size(), 50);
        }

        public Object getElementAt(int index) {
            ISong song = songs.get(index);
            return "<html>" + song.getName() + ", <i>" + song.getAuthor().getName() + "</i></html>" ;
        }
        
        public ISong getSongAt(int index) {
            return songs.get(index);
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        songList = new org.jdesktop.swingx.JXList();
        searchField = new javax.swing.JTextField();
        jXLabel1 = new org.jdesktop.swingx.JXLabel();
        jXTitledSeparator1 = new org.jdesktop.swingx.JXTitledSeparator();

        jScrollPane1.setViewportView(songList);

        searchField.setText(org.openide.util.NbBundle.getMessage(AddSongsPanel.class, "AddSongsPanel.searchField.text", new Object[] {})); // NOI18N
        searchField.setToolTipText(org.openide.util.NbBundle.getMessage(AddSongsPanel.class, "AddSongsPanel.searchField.toolTipText",new Object[] {})); // NOI18N

        jXLabel1.setDisplayedMnemonic('H');
        jXLabel1.setText(org.openide.util.NbBundle.getMessage(AddSongsPanel.class, "AddSongsPanel.jXLabel1.text", new Object[] {})); // NOI18N
        jXLabel1.setToolTipText(org.openide.util.NbBundle.getMessage(AddSongsPanel.class, "AddSongsPanel.jXLabel1.toolTipText",new Object[] {})); // NOI18N

        jXTitledSeparator1.setToolTipText(org.openide.util.NbBundle.getMessage(AddSongsPanel.class, "AddSongsPanel.jXTitledSeparator1.toolTipText")); // NOI18N
        jXTitledSeparator1.setFont(jXTitledSeparator1.getFont().deriveFont(jXTitledSeparator1.getFont().getStyle() | java.awt.Font.BOLD, jXTitledSeparator1.getFont().getSize()+1));
        jXTitledSeparator1.setTitle(org.openide.util.NbBundle.getMessage(AddSongsPanel.class, "AddSongsPanel.jXTitledSeparator1.title", new Object[] {})); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jXLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(searchField, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)
                        .addGap(105, 105, 105))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jXTitledSeparator1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jXTitledSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jXLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXLabel jXLabel1;
    private org.jdesktop.swingx.JXTitledSeparator jXTitledSeparator1;
    private javax.swing.JTextField searchField;
    private org.jdesktop.swingx.JXList songList;
    // End of variables declaration//GEN-END:variables

}
